//---------------------------------------------------------------------------- Package
const _ = require('lodash')
//---------------------------------------------------------------------------- Config
const { MYSQL } = require('../../config')
//---------------------------------------------------------------------------- Plugin
const mysql = require('../../plugin/util/mysql')
const sheet = require('../../plugin/util/sheet')
const log = require('../../plugin/util/log')
const fs = require('fs')
const nodeExcel = require('excel-export')

// ---------------------------------------------------------------------------- GET
exports.get = {

  '/test/testlist':async(ctx, next)=>{
    let sql = ["select name from school_detail"];
    let data = await mysql.query(MYSQL.XIONGAN, sql, []);
    sheet[0].data = data[0];
    ctx.body = sheet[0];
  },

  /**
   * 培训学校列表
   */ 
  '/cultivate/school/list': async (ctx,next) => {
    let where = ''
    let limit = ' limit 0,10'
    if(ctx.query.id){
      where = where == ''? ' where id = ' + ctx.query.id : where + ' and id = ' + ctx.query.id
    }
    if(ctx.query.category){
      where = where == ''? ' where category = ' + ctx.query.category : where + ' and category = ' + ctx.query.category
    }
    if(ctx.query.type){
      where = where == ''? ' where type = ' + ctx.query.type : where + ' and type = ' + ctx.query.type
    }
    if(ctx.query.show){
      where = where == ''? ' where `show` = ' + ctx.query.show : where + ' and `show` = ' + ctx.query.show
    }
    if(ctx.query.name){
      where = where == ''? ' where name like "%' + ctx.query.name + '%"' : where + ' and name like "%' + ctx.query.name + '%"'
    }                                      
    if(ctx.query.page > 0){
      limit = ' limit ' + (ctx.query.page-1)*10 + ',10'
    }
    let list = await mysql.query(MYSQL.XIONGAN, ['select * from school_detail' + where + limit], [])
    for(let i=0; i<list[0].length; i++){
      let imgs = await mysql.query(MYSQL.XIONGAN, ['select url from vantage_swiper where sid = ?'], [list[0][i].id])
      list[0][i].imgs = imgs[0]
    }
    sheet[0].data = list
    ctx.body = sheet[0]
  },
  /**
   * 培训课程列表
   */ 
  '/cultivate/cultivate/list': async (ctx,next) => {
    let where = ''
    let limit = ' limit 0,10'
    if(ctx.query.id){
      where = where == ''? ' where id = ' + ctx.query.id : where + ' and id = ' + ctx.query.id
    }
    if(ctx.query.sid){
      where = where == ''? ' where sid = ' + ctx.query.sid : where + ' and sid = ' + ctx.query.sid
    }
    if(ctx.query.ishome){
      where = where == ''? ' where ishome = ' + ctx.query.ishome : where + ' and ishome = ' + ctx.query.ishome
    }
    if(ctx.query.show){
      where = where == ''? ' where `show` = ' + ctx.query.show : where + ' and `show` = ' + ctx.query.show
    }
    if(ctx.query.name){
      where = where == ''? ' where name like "%' + ctx.query.name + '%"' : where + ' and name like "%' + ctx.query.name + '%"'
    }
    if(ctx.query.page > 0){
      limit = ' limit ' + (ctx.query.page-1)*10 + ',10'
    }
    let list = await mysql.query(MYSQL.XIONGAN, ['select * from cultivate' + where + limit], [])
    for(let i=0; i<list[0].length; i++){
      let sname = await mysql.query(MYSQL.XIONGAN, ['select * from school_detail where id = ?'], [list[0][i].sid])
      if(sname[0].length > 0){
        list[0][i].sname = sname[0][0].name
        list[0][i].school_show = sname[0][0].show
      }
    }
    sheet[0].data = list
    ctx.body = sheet[0]
  },
  /**
   * 培训课期列表
   */ 
  '/cultivate/semester/list': async (ctx,next) => {
    let where = ''
    let limit = ' limit 0,10'
    if(ctx.query.id){
      where = where == ''? ' where id = ' + ctx.query.id : where + ' and id = ' + ctx.query.id
    }
    if(ctx.query.sid){
      where = where == ''? ' where sid = ' + ctx.query.sid : where + ' and sid = ' + ctx.query.sid
    }
    if(ctx.query.culid){
      where = where == ''? ' where culid = ' + ctx.query.culid : where + ' and culid = ' + ctx.query.culid
    }
    if(ctx.query.ishistory){
      where = where == ''? ' where ishistory = ' + ctx.query.ishistory : where + ' and ishistory = ' + ctx.query.ishistory
    }
    if(ctx.query.show){
      where = where == ''? ' where `show` = ' + ctx.query.show : where + ' and `show` = ' + ctx.query.show
    }
    if(ctx.query.name){
      where = where == ''? ' where name like "%' + ctx.query.name + '%"' : where + ' and name like "%' + ctx.query.name + '%"'
    }
    if(ctx.query.page > 0){
      limit = ' limit ' + (ctx.query.page-1)*10 + ',10'
    }
    let list = await mysql.query(MYSQL.XIONGAN, ['select * from semester' + where + limit], [])
    let time = Date.parse( new Date() ).toString().substr(0,10)
    for(let i=0; i<list[0].length; i++){
      // 把课程结束时间在此时间之前ishistory状态改为1（课程已结束）
      if(list[0][i].ishistory == 0 && list[0][i].class_endtime < time){
        await mysql.query(MYSQL.XIONGAN, ['update semester set ishistory = 1 where id = ?'], [list[0][i].id])
        list[0][i].ishistory = 1
      }
      let sname = await mysql.query(MYSQL.XIONGAN, ['select * from school_detail where id = ?'], [list[0][i].sid])
      list[0][i].sname = sname[0][0].name
      list[0][i].school_show = sname[0][0].show
      let culname = await mysql.query(MYSQL.XIONGAN, ['select * from cultivate where id = ?'], [list[0][i].culid])
      list[0][i].culname = culname[0][0].name
      list[0][i].cultivate_show = culname[0][0].show
    }
    sheet[0].data = list
    ctx.body = sheet[0]
  },
  /**
   * 报名列表
   */ 
  '/apply/list': async (ctx,next) => {
    let where = ''
    let limit = ' limit 0,15'
    let arg = []
    if(ctx.query.page > 0){
			limit = ' limit ' + (ctx.query.page-1)*10 + ',15'
    }
    let user=[]
    let company = []
    let status = ctx.query.status
    let apply=[]
    let cul = await mysql.query(MYSQL.XIONGAN,['select * from apply_record where status='+ status + limit],arg)
    for (let v of cul[0]){
      if(v.type=='user'){
        let user = await mysql.query(MYSQL.XIONGAN,['select * from resume where uid=?'],[v.uid])
        v.uname = user[0][0].name
        v.umobile = user[0][0].mobile
      }
      else{
        let company = await mysql.query(MYSQL.XIONGAN,['select * from company where id=?'],[v.cid])
        v.uname = company[0][0].name
        v.umobile = company[0][0].contact_mobile
      }
      let sname = await mysql.query(MYSQL.XIONGAN, ['select name from school_detail where id = ?'], [v.sid])
      v.sname = sname[0][0].name
      let culname = await mysql.query(MYSQL.XIONGAN, ['select name from cultivate where id = ?'], [v.culid])
      v.culname = culname[0][0].name
      let semname = await mysql.query(MYSQL.XIONGAN, ['select name from semester where id = ?'], [v.semid])
      v.semname = semname[0][0].name
    }
    sheet[0].data = cul[0]
    ctx.body = sheet[0]
  },
  /**
   * 培训轮播图列表
   */ 
  '/cultivate/swiper/list': async (ctx,next) => {
    let where = ''
    let limit = ' limit 0,10'
    if(ctx.query.culid){
      where = where == ''? ' where culid = ' + ctx.query.culid : where + ' and culid = ' + ctx.query.culid
    }
    if(ctx.query.sid){
      where = where == ''? ' where sid = ' + ctx.query.sid : where + ' and sid = ' + ctx.query.sid
    }
    if(ctx.query.page > 0){
			limit = ' limit ' + (ctx.query.page-1)*10 + ',10'
    }
    let list = await mysql.query(MYSQL.XIONGAN,['select * from class_swiper' + where + limit],null)
    for (let v of list[0]){
      v.sname = ''
      v.culname = ''
      if(v.sid){
        let sname = await mysql.query(MYSQL.XIONGAN, ['select name from school_detail where id = ?'], [v.sid])
        v.sname = sname[0][0].name
      }
      if(v.culid){
        let culname = await mysql.query(MYSQL.XIONGAN, ['select name from cultivate where id = ?'], [v.culid])
        v.culname = culname[0][0].name
      }
    }
    sheet[0].data = list[0]
    ctx.body = sheet[0]
  },

  //获取线下听课者的列表
  '/get/cultivateapplyinfo/info':async(ctx,next) =>{
    let {page} = ctx.query
    if(_.isUndefined(page)){
      page=1
    }
    page = (page < 1) ? 0 : (page-1)
    let num = 15
    let sql = 'select cultivate_applyinfo.*,cultivate.name as cul_name from cultivate_applyinfo left join cultivate on cultivate_applyinfo.cul_id=cultivate.id order by  time_create desc  limit ?,?'
    let arg = [parseInt(page) * num,num]
    let info = await mysql.query(MYSQL.XIONGAN,[sql],arg)
    sheet[0].data = info[0]
    ctx.body = sheet[0]
    return 
  },

  //获取登录参加培训人员列表
  '/get/culpayuserlist/list':async(ctx,next) =>{
    let {page} = ctx.query
    console.log(page)
    if(_.isUndefined(page)){
      page=1
    }
    page = (page < 1) ? 0 : (page-1)
    let num = 15
    let sql = 'select * from user where is_reg=1 limit ?,?'
    let arg = [parseInt(page) * num,num]
    let info = await mysql.query(MYSQL.XIONGAN,[sql],arg)
    sheet[0].data = info[0]
    ctx.body = sheet[0]
    return 
  },

  //课程购买记录
  '/get/culpayuserlistpay/list':async(ctx,next) =>{
    let {page} = ctx.query
    console.log(page)
    if(_.isUndefined(page)){
      page=1
    }
    page = (page < 1) ? 0 : (page-1)
    let num = 15
    let sql = 'select B.*,C.name as sname,A.paytime from curl_pay_rel as A left join user as B on A.uid = B.id left join school_detail as C on A.sid=C.id where ispay=1 limit ?,?'
    let arg = [parseInt(page) * num,num]
    let info = await mysql.query(MYSQL.XIONGAN,[sql],arg)
    sheet[0].data = info[0]
    ctx.body = sheet[0]
    return 
  },

  /**
   * 获取线下听课者的列表总条数
   */
  '/get/cultivateapplyinfo/count':async(ctx,next) =>{
    let sql = 'select count(id) as countnum from cultivate_applyinfo'
    let info = await mysql.query(MYSQL.XIONGAN,[sql],[])
    sheet[0].data = info[0]
    ctx.body = sheet[0]
    return 
  },

    /**
   * 获取线下听课者信息excel
   */
  '/get/excel/cultivateapplyinfo/info':async(ctx,next) =>{
    let sql = 'select * from cultivate_applyinfo order by  time_create desc'
    let arg = []
    let info = await mysql.query(MYSQL.XIONGAN,[sql],arg)
    for(let i of info[0]){
      i.time_create = new Date(i.time_create*1000).format('yyyy-MM-dd hh:mm:ss')
      i.time_check = new Date(i.time_check*1000).format('yyyy-MM-dd hh:mm:ss')
      if(i.islink == 1){
        i.islink = '是'
      }else{
        i.islink = '否'
      }
    }
    let conf={};
    conf.cols = [
      {caption:'姓名',type:'string'},
      {caption:'电话',type:'string'},
      {caption:'发布时间',type:'string'},
      {caption:'反馈时间',type:'string'},
      {caption:'备注',type:'string'},
      {caption:'是否反馈',type:'string'},
    ];
    conf.rows = []
    for(let i of info[0]){
      conf.rows.push([i.username,i.mobile,i.time_create,i.time_check,i.remark,i.islink])
    }
    let xls_data = nodeExcel.execute(conf);
    let data = new Buffer(xls_data,'binary')
    ctx.set('Content-Type', 'application/octet-stream');
    ctx.set("Content-Disposition", "attachment; filename=" + "jobseekers.csv");
    ctx.body = data
    return
  },


  /**
   * 获取题目列表
   */
  '/get/question/list':async(ctx,next) =>{
    let {page, question, sid} = ctx.query
    let where = "";
    if(question != "" && question){
      where += ' and question like "%' + question + '%" '
    }
    if(sid!="" && sid){
      where += ' and sid='+sid
    }

    where = 'where id>0 ' + where

    if(_.isUndefined(page)){
      page=1
    }
    page = (page < 1) ? 0 : (page-1)
    let num = 15


    let sql = 'select * from cul_question '+ where +' order by sort desc,convert(question using gbk) limit ?,?'
    let arg = [parseInt(page) * num,num]
    let info = await mysql.query(MYSQL.XIONGAN,[sql],arg)

    let count = await mysql.query(MYSQL.XIONGAN,['select count(id) as count from cul_question ' + where],[])
    count = count[0][0]['count']
    let pagesnum = Math.ceil(count/num);

    sheet[0].data = {
      list:info,
      count:count,
      pagesnum:pagesnum,
      page:page+1,
    }

    ctx.body = sheet[0]
    return 
  },


  /**
   * 获取要编辑的页面的详情
   */
  '/get/question/info':async(ctx,next) =>{
    let id = ctx.query.id
    let sql = 'select * from cul_question where id=?';
    let info = await mysql.query(MYSQL.XIONGAN,[sql],[id])
    sheet[0].data = info[0][0]
    ctx.body = sheet[0]
    return 
  },

  /**
   * 删除课程 by
   *  id
   * 
   */
  '/get/delete/cultivate/:id':async(ctx,next) =>{
    let id = ctx.params.id
    mysql.query(MYSQL.XIONGAN, ['delete from cultivate where id=?'], [id]);
  },



}
// ---------------------------------------------------------------------------- POST
exports.post = {
  /**
   * 培训学校/机构添加
   */
  '/cultivate/add/school' : async (ctx, next) => {
    let {show, category, type, name, address, img, summary, merit, sort, imgs, needfee, price, qprice, aprice, quesimg} = ctx.request.fields
    show = 0
    let data = await mysql.query(MYSQL.XIONGAN, ['insert into school_detail (`show`, category, type, name, address, img, summary, merit, sort, needfee, price, qprice, aprice, quesimg) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)'], [ show, category, type, name, address, img, summary, merit, sort, needfee, price, qprice, aprice, quesimg])
    for(let i=0; i< imgs.length; i++){
      await mysql.query(MYSQL.XIONGAN, ['insert into vantage_swiper (sid, url) values (?,?)'], [ data[0].insertId, imgs[i]])
    }
    sheet[0].message = '添加成功'
    ctx.body = sheet[0]
  },
  /**
   * 培训课程添加
   */
  '/cultivate/add/cultivate' : async (ctx, next) => {
    let postdata = ctx.request.fields;
    let add_sql_arr = [];//字段数组
    let add_sql_value_arr = [];//值数组
    let add_sql_value_palceholder_arr = [];//占位符
    let not_add_fields = ['number'];//占位符

    for(var key in postdata){
      if(key.indexOf(not_add_fields)>-1){
        continue;
      };
      // if(key == "c_time"){
      //   postdata[key] = Date.parse(new Date(postdata[key].replace(/\T/g,' '))).toString().slice(0,10);
      // };
      add_sql_arr.push("`"+key+"`");
      add_sql_value_arr.push(postdata[key]);
      add_sql_value_palceholder_arr.push("?");
    };
    let add_sql_str = add_sql_arr.join(",");//字段字符串
    let add_sql_value_palceholder_str = add_sql_value_palceholder_arr.join(",");//占位符字符串
    let list = await mysql.query(MYSQL.XIONGAN, ['select * from cultivate where sid = ? and ishome = 1'], [postdata['sid']]);
    if(list[0].length >= 3 && postdata['ishome'] == 1){
      sheet[10004].message = '抱歉，在首页显示的课程已经为3个，不能在设置在首页显示，请重新设置！'
      ctx.body = sheet[10004]
      return
    };
    let data = await mysql.query(MYSQL.XIONGAN, ['insert into cultivate ('+add_sql_str+') values ('+add_sql_value_palceholder_str+')'], add_sql_value_arr);
    sheet[0].message = '添加成功';
    ctx.body = sheet[0];



    // let {show, sid, name, mobile, icon, content, target, system, direction, ishome} = ctx.request.fields
    // let list = await mysql.query(MYSQL.XIONGAN, ['select * from cultivate where sid = ? and ishome = 1'], [sid])
    // if(list[0].length >= 3 && ishome == 1){
    //   sheet[10004].message = '抱歉，在首页显示的课程已经为3个，不能在设置在首页显示，请重新设置！'
    //   ctx.body = sheet[10004]
    //   return
    // }
    // let data = await mysql.query(MYSQL.XIONGAN, ['insert into cultivate (`show`, sid, name, mobile, icon, content, target, system, direction, ishome) values (?,?,?,?,?,?,?,?,?,?)'], [ show, sid, name, mobile, icon, content, target, system, direction, ishome])
    // sheet[0].message = '添加成功'
    // ctx.body = sheet[0]
  },
  /**
   * 培训课期添加
   */
  '/cultivate/add/semester' : async (ctx, next) => {
    let {show, sid, culid, name, class_starttime, class_endtime, apply_endtime, content, target, system, history_img } = ctx.request.fields
    class_starttime = Date.parse(new Date(class_starttime.replace(/\T/g,' '))).toString().slice(0,10)
    class_endtime = Date.parse(new Date(class_endtime.replace(/\T/g,' '))).toString().slice(0,10)
    apply_endtime = Date.parse(new Date(apply_endtime.replace(/\T/g,' '))).toString().slice(0,10)
    let data = await mysql.query(MYSQL.XIONGAN, ['insert into semester (`show`, sid, culid, name, class_starttime, class_endtime, apply_endtime, content, target, system, history_img) values (?,?,?,?,?,?,?,?,?,?,?)'], [ show, sid, culid, name, class_starttime, class_endtime, apply_endtime, content, target, system, history_img])
    sheet[0].message = '添加成功'
    ctx.body = sheet[0]
  },
  /**
   * 培训轮播图添加
   */
  '/cultivate/add/swiper' : async (ctx, next) => {
    let {sid, culid, url } = ctx.request.fields
    let data = await mysql.query(MYSQL.XIONGAN, ['insert into class_swiper (sid, culid, url) values (?,?,?)'], [ sid, culid, url])
    sheet[0].message = '添加成功'
    ctx.body = sheet[0]
  },

  /**
  *添加题目
  */
 '/question/add/question' : async (ctx, next) => {
  let {         
    sid,
    question,
    answer,
    rightanswer,
    img,
    type
  } = ctx.request.fields
  let data = await mysql.query(MYSQL.XIONGAN, ['insert into cul_question (sid,question,answer,rightanswer,img,type) values (?,?,?,?,?,?)'], [sid,question,answer,rightanswer,img,type])
    sheet[0].message = '添加成功'
    ctx.body = sheet[0]
  },




}
// ---------------------------------------------------------------------------- PUT
exports.put = {
  /**
   * 行更新排序
   */
  '/cultivate/school/sort': async (ctx, next) => {
    if (!_.isArray(ctx.request.fields)) {
      ctx.request.fields = [ctx.request.fields]
    }
    let sql = []
    let arg = []
    for (let item of ctx.request.fields) {
      let { sort, id } = item
      sql.push('update school_detail set sort=? where id=?')
      arg.push([sort, id])
    }
    await mysql.query(MYSQL.XIONGAN, sql, arg)
    sheet[0].message = '更新成功!'
    ctx.body = sheet[0]
  },
  /**
   * 行更新课程是否在首页显示
   */
  '/cultivate/cultivate/ishome': async (ctx, next) => {
    if (!_.isArray(ctx.request.fields)) {
      ctx.request.fields = [ctx.request.fields]
    }
    let sql = []
    let arg = []
    for (let item of ctx.request.fields) {
      let { ishome, sort, id } = item
      sql.push('update cultivate set ishome=?, sort=? where id=?')
      arg.push([ishome, sort, id])
    }
    await mysql.query(MYSQL.XIONGAN, sql, arg)
    sheet[0].message = '更新成功!'
    ctx.body = sheet[0]
  },

   /**
   * 题目更新排序
   */
  '/cultivate/question/sort': async (ctx, next) => {
    if (!_.isArray(ctx.request.fields)) {
      ctx.request.fields = [ctx.request.fields]
    }
    let sql = []
    let arg = []
    for (let item of ctx.request.fields) {
      let { sort, id } = item
      sql.push('update cul_question set sort=? where id=?')
      arg.push([sort, id])
    }
    await mysql.query(MYSQL.XIONGAN, sql, arg)
    sheet[0].message = '更新成功!'
    ctx.body = sheet[0]
  },

  /**
   * 培训学校/机构编辑
   */
  '/cultivate/edit/school' : async (ctx, next) => {
    let {show, category, type, name, address, img, summary, merit, sort, id, imgs, needfee, price, qprice, aprice, quesimg} = ctx.request.fields
    let data = await mysql.query(MYSQL.XIONGAN, ['update school_detail set `show`=?, category = ?, type = ?, name = ?, address = ?, img = ?, summary = ?, merit = ?, sort = ?, needfee=?, price=?, qprice=?, quesimg=?, aprice=? where id = ?'], [ show, category, type, name, address, img, summary, merit, sort, needfee, price, qprice, quesimg, aprice, id])
    await mysql.query(MYSQL.XIONGAN, ['delete from vantage_swiper where sid =?'], [id])
    for(let i=0; i< imgs.length; i++){
      await mysql.query(MYSQL.XIONGAN, ['insert into vantage_swiper (sid, url) values (?,?)'], [ id, imgs[i]])
    }
    if(show != 0){
      await mysql.query(MYSQL.XIONGAN, ['update cultivate set `show`=? where sid = ?'], [ show,id])
      await mysql.query(MYSQL.XIONGAN, ['update semester set `show`=? where sid = ?'], [ show,id])
    }
    sheet[0].message = '编辑成功'
    ctx.body = sheet[0]
  },
  /**
   * 培训课程编辑
   */
  '/cultivate/edit/cultivate' : async (ctx, next) => {
    let post_data = ctx.request.fields;
    let mid_add_sql_arr = [];
    let mid_add_sql_value_arr = [];
    let not_update_fields_arr = ["id", "sname","school_show"];//不加入更新的字段
    for(var key in post_data){
      if(not_update_fields_arr.indexOf(key) > -1){
        continue;
      }
      // if(key == "c_time"){
      //   post_data[key] = Date.parse(new Date(post_data[key].replace(/\T/g,' '))).toString().slice(0,10);
      // }
      mid_add_sql_arr.push("`"+key+"`=?");
      mid_add_sql_value_arr.push(post_data[key]);
    }
    let mid_add_sql_str = mid_add_sql_arr.join(",");//有数组转成sql
    mid_add_sql_value_arr.push(post_data["id"]);//添加id
    //let {show, sid, name, mobile, icon, content, target, system, direction, ishome, id} = ctx.request.fields
    let list = await mysql.query(MYSQL.XIONGAN, ['select * from cultivate where sid = ? and ishome = 1'], [post_data['sid']])
    let one = await mysql.query(MYSQL.XIONGAN, ['select * from cultivate where sid = ? and ishome = 1 and id=?'], [post_data['sid'], post_data['id']])
    if(list[0].length >= 3 && one[0].length == 0 && ishome == 1){
      sheet[10004].message = '抱歉，在首页显示的课程已经为3个，不能在设置在首页显示，请重新设置！'
      ctx.body = sheet[10004]
      return
    }
    let data = await mysql.query(MYSQL.XIONGAN, ['update cultivate set '+mid_add_sql_str+' where id = ?'], mid_add_sql_value_arr)
    if(post_data['show'] != 0){
      await mysql.query(MYSQL.XIONGAN, ['update semester set `show`=? where culid = ?'], [ post_data['show'],post_data['id']])
    }
    sheet[0].message = '编辑成功'
    ctx.body = sheet[0]
  },
  /**
   * 培训课期编辑
   */
  '/cultivate/edit/semester' : async (ctx, next) => {
    let {show, sid, culid, name, class_starttime, class_endtime, apply_endtime, content, target, system, history_img, id } = ctx.request.fields
    class_starttime = Date.parse(new Date(class_starttime.replace(/\T/g,' '))).toString().slice(0,10)
    class_endtime = Date.parse(new Date(class_endtime.replace(/\T/g,' '))).toString().slice(0,10)
    apply_endtime = Date.parse(new Date(apply_endtime.replace(/\T/g,' '))).toString().slice(0,10)
    let data = await mysql.query(MYSQL.XIONGAN, ['update semester set `show`=?, sid=?, culid=?, name=?, class_starttime=?, class_endtime=?, apply_endtime=?, content=?, target=?, system=?, history_img=? where id = ?'], [ show, sid, culid, name, class_starttime, class_endtime, apply_endtime, content, target, system, history_img, id])
    sheet[0].message = '编辑成功'
    ctx.body = sheet[0]
  },

  /**
   * 更新线下听课者的信息
   */
  '/update/cultivateapplyinfo':async (ctx,next) =>{
    let {id,islink,remark} = ctx.request.fields
    let time = Date.parse(new Date()).toString().substr(0,10)
    let sql = 'update cultivate_applyinfo set islink=?,time_check=?,remark=? where id=?'
    let arg = [islink,time,remark,id]
    await mysql.query(MYSQL.XIONGAN,[sql],arg)
    sheet[0].data = []
    ctx.body = sheet[0]
  },

  /*
  设置为设置为初始课程
   */
  '/cultivate/init_cul':async (ctx,next) =>{
    let put_data = ctx.request.fields;
    put_data.active_init = 1;
    let mid_sql = [];
    let values_arr = [];
    for(var key in put_data){
      var sql = key+"=?"
      mid_sql.push(sql);
      values_arr.push(put_data[key]);
    }
    let mid_sql_str = mid_sql.join(",");

    let excute_sql_init = "update cultivate set active_init=0 where sid="+put_data['sid'];
    await mysql.query(MYSQL.XIONGAN,[excute_sql_init],[]);
    
    let excute_sql = "update cultivate set "+mid_sql_str+" where id="+put_data['id'];
    await mysql.query(MYSQL.XIONGAN,[excute_sql],values_arr);
    sheet[0].data = [];
    ctx.body = sheet[0];
  },

  /**
  *编辑题目
  */
 '/question/edit/question' : async (ctx, next) => {
  let {   
    id,      
    sid,
    question,
    answer,
    rightanswer,
    important,
    img,
    type
  } = ctx.request.fields

  let data = await mysql.query(MYSQL.XIONGAN, ['update cul_question set sid=?,question=?,answer=?,rightanswer=?,important=?,img=?,type=? where id=?'], [sid,question,answer,rightanswer,important,img,type,id])
    sheet[0].message = '编辑成功'
    ctx.body = sheet[0]
  },

} 
// ---------------------------------------------------------------------------- DELETE
exports.delete = {
 /**
   * 培训课程轮播图删除
   */
  '/cultivate/delete/swiper/:id': async (ctx, next) => {
    let id = ctx.params.id
    let data=await mysql.query(MYSQL.XIONGAN, ['delete from class_swiper where id =?'], [id])
    sheet[0].message = '删除成功'
    ctx.body = sheet[0]
  },

  /**
   * 培训学校或者机构删除
   */
  '/cultivate/delete/school': async (ctx, next) => {
    let id = ctx.query.id
    await mysql.query(MYSQL.XIONGAN, ['delete from cultivate where sid =?'], [id])
    await mysql.query(MYSQL.XIONGAN, ['delete from school_detail where id =?'], [id])
    sheet[0].message = '删除成功'
    ctx.body = sheet[0]
  },

  /**
   * 删除问题
   */
  '/cultivate/delete/question': async (ctx, next) => {
    let id = ctx.query.id
    await mysql.query(MYSQL.XIONGAN, ['delete from cul_question where id =?'], [id])
    sheet[0].message = '删除成功'
    ctx.body = sheet[0]
  },
}